<script setup>
import { watch } from 'vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
  fileList: {
    type: Array || String,
    default: () => []
  }
})

const downloadFile = (url, fileName, flieId, type) => {
  window.open(url)
}

function frontDownload(fileUrl, fileName) {
  // 发送Ajax请求获取文件二进制数据
  axios({
    url: fileUrl,
    method: 'GET',
    responseType: 'blob',
    data: {}
  }).then(response => {
    var fileURL = window.URL.createObjectURL(new Blob([response]))
    var fileLink = document.createElement('a')
    fileLink.href = fileURL
    fileLink.setAttribute('download', fileName)
    document.body.appendChild(fileLink)
    fileLink.click()
  })
}

const download = val => {
  // frontDownload(val)
  downloadFile(val)
  // proxy.download(val, `${getFileName(val)}${new Date().getTime()}.${val.slice(val.lastIndexOf('.') + 1)}`)
}

// 获取文件名称
function getFileName(name) {
  if (name && name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1)
  } else {
    return '暂无附件信息，请上传附件'
  }
}
const arrList = ref([])
// 转义为数组
watch(
  () => props.fileList,
  val => {
    if (Array.isArray(val)) {
      arrList.value = val
    } else {
      if (val?.length > 3) {
        arrList.value = val.split(',')
      } else {
        arrList.value = []
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div class="app-">
    <div class="box flex" v-for="(item, index) in arrList" :key="index">
      <el-link v-if="getFileName(item) != '暂无附件信息，请上传附件'" @click="download(item)" target="_blank">
        {{ getFileName(item) }}</el-link
      >
      <div v-else target="_blank">{{ getFileName(item) }}</div>
    </div>
    <el-link v-if="arrList.length <= 0" target="_blank"> 暂无附件信息,请上传附件 </el-link>
  </div>
</template>

<style lang="scss" scoped>
.box {
  display: flex;
  padding: 5px;
  align-items: center;
  color: black;
  z-index: 999;
}
</style>
